package com.lstimeline.utility.DataManager;

import com.lstimeline.bean.UserBean;
import com.lstimeline.utility.AeSimpleSHA1;

import java.sql.*;


public class LoginDataManager extends AbstractDataManager {
	/**
	 * Return a userbean if the user exists, null otherwise
	 * username is case insensitive
	 * password is case sensitive
	 */
	public static UserBean getUserData(String username, String password) {
		boolean isSuccessful = false;
		UserBean userBean = new UserBean();
		Connection conn = getConnection();
		if(conn != null) {
			PreparedStatement ps = null;
			ResultSet rs = null;
			try {
				String queryString = "SELECT userid, regtime, usergroup, username FROM user WHERE username=? AND password=?";
				String encryptedPassword = AeSimpleSHA1.SHA1(password);
				
				ps = conn.prepareStatement(queryString);
				ps.setString(1, username.toUpperCase());
				ps.setString(2, encryptedPassword);
				
				rs = ps.executeQuery();
				
				while(rs.next()) {
					userBean.setUserid(rs.getString("userid"));
					userBean.setRegtime(rs.getString("regtime"));
					userBean.setUsergroup(rs.getString("usergroup"));
					userBean.setUsername(rs.getString("username"));
				}
				
				isSuccessful = userBean.getUserid() != null; //important, flag the query as successful
			} catch(Exception e) {
				e.printStackTrace();
			} finally {
				try {
					rs.close();
					ps.close();
					closeConnection(conn);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			
			if(isSuccessful) {
				return userBean;
			} else {
				return null;
			}
		} else {
			// conn is not opened
			return null;
		}
	}
}
